
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include "dhtxx.h"
#include "common.h"

#define DATA_PIN        rt_pin_get("PB.0")

#define ADC_DEV_NAME        "adc0"      /* ADC 设备名称 */
#define ADC_DEV_CHANNEL     3           /* ADC 通道 */

All_Data_Struct s_m_current_data;

static rt_adc_device_t device_adc_find()
{
    rt_adc_device_t adc_dev;
    /* 查找设备 */
    adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);
    if (adc_dev == RT_NULL)
    {
        rt_kprintf("adc sample run failed! can't find %s device!\n", ADC_DEV_NAME);
        return RT_NULL;
    }
    
    /* 使能设备 */
    rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);
    return adc_dev;
}

void sensor_process(void *avg)
{
    dht_device_t sensor = dht_create(DATA_PIN);
    rt_adc_device_t adc_dev = device_adc_find();

    if(sensor == RT_NULL || adc_dev == RT_NULL)
        return ;
#if 0
    rt_kprintf("rt-thread %lu \n", rt_tick_get());
    rt_hw_us_delay(1000*1000);
    rt_kprintf("rt-thread %lu \n", rt_tick_get());
#endif

    rt_memset(&s_m_current_data, 0, sizeof(All_Data_Struct));
    while(1)
    {
        rt_thread_mdelay(1000);

        s_m_current_data.illuminance = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);

        if(dht_read(sensor)) {

            s_m_current_data.temperature = dht_get_temperature(sensor);
            s_m_current_data.humidity = dht_get_humidity(sensor);

//           rt_kprintf("Temp: %02d.%d, Humi: %02d.%d \n", \
//                    s_m_current_data.temperature/10, s_m_current_data.temperature%10, \
//                    s_m_current_data.humidity/10, s_m_current_data.humidity%10);
        }
        else {
            rt_kprintf("Read dht sensor failed.\n");
        }
    }
    dht_delete(sensor);
}


static int sensor_thread_create(void)
{
    rt_thread_t sensor_thread;

    sensor_thread = rt_thread_create("sensor_thread", sensor_process, 
                                    RT_NULL, 1024, 
                                    18, 20);
    
    if (sensor_thread) 
        return rt_thread_startup(sensor_thread);
    else 
        return RT_ERROR;
}

INIT_APP_EXPORT(sensor_thread_create);
